package gold.digger;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC1209 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public String removeDuplicates(String s, int k) {
            StringBuilder res = new StringBuilder();
            char lastCh = ' ';
            int lastRepeatLen = 1, repeatInResLen = 0;
            for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) == lastCh && ++lastRepeatLen == k) {
                    //进入重复字符阶段，需要计数看是否重复长度达到k
                    lastRepeatLen = 1;
                    for (int j = 0; j < k - 1; j++) {
                        res.deleteCharAt(res.length() - 1);//删除末尾字符
                    }
                    for (int j = res.length() - 2; j >= 0; j--) {
                        if (res.charAt(j) == res.charAt(res.length() - 1)) ++lastRepeatLen;
                        else break;
                    }
                    lastCh = res.length() == 0 ? ' ' : res.charAt(res.length() - 1);
                } else {
                    if (s.charAt(i) != lastCh) lastRepeatLen = 1;
                    res.append(s.substring(i, i + 1));
                    lastCh = s.charAt(i);
                }
            }

            return res.toString();
        }
    }

    public void run() {
        Solution solution = new Solution();
//        输入：s = "deeedbbcccbdaa", k = 3
//        输出："aa"
//        解释：
//        先删除 "eee" 和 "ccc"，得到 "ddbbbdaa"
//        再删除 "bbb"，得到 "dddaa"
//        最后删除 "ddd"，得到 "aa"
        System.out.println(solution.removeDuplicates("deeedbbcccbdaa", 3));
        System.out.println(solution.removeDuplicates("ghanyhhhhhttttttthhyyyyyynnnnnnyqkkkkkkkrrrrrrjjjjjjjryyyyyyfffffffygq", 7));
    }

    public static void main(String[] args) throws Exception {
        LC1209 an = new LC1209();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
